package com.csxy.news.servlet;

import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.csxy.news.util.VerifyCodeUtil;
import com.csxy.news.util.WebUtil;

/**
 * Servlet implementation class VerfiyCodeServlet
 */
public class VerfiyCodeServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private int width;
	private int height;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public VerfiyCodeServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Servlet#init(ServletConfig)
	 */
	public void init(ServletConfig config) throws ServletException {
		this.width=Integer.parseInt(config.getInitParameter(WebUtil.WIDTH));
		this.height=Integer.parseInt(config.getInitParameter(WebUtil.HEIGHT));
	}

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		//告诉浏览器不要对页面进行缓存
		WebUtil.noCache(response);
        
		//随机生成验证码与验证码图片
        
        WebUtil.useImageContentType(response);
        OutputStream os=response.getOutputStream();
		String verifyCode=VerifyCodeUtil.outputVerifyImage(this.width, this.height, os, 4);
		//将验证码保存到用户级的上下文中，以便登录时进行验证
		WebUtil.saveVerifyCode(request, verifyCode);
		
	}

}
